<template>
  <el-tree
    :data="allData"
    v-if="data.length"
    default-expand-all
    :render-content="render"
  ></el-tree>
</template>

<script>
import _ from "lodash";
export default {
  props: {
    data: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      allData: [],
    };
  },
  methods: {
    transformData() {
      // {1: {name: '文件夹1', pid: 0, id: 1}}
      // 深拷贝,为了防止在子组件中操作父组件的数据
      let AllData = _.cloneDeep(this.data);
      let treeMapList = AllData.reduce((memo, current) => {
        // current.label = current.name;
        memo[current["id"]] = current;
        return memo;
      }, {});

      let result = AllData.reduce((arr, current) => {
        let pid = current.pid;
        let parent = treeMapList[pid];
        if (parent) {
          parent.children
            ? parent.children.push(current)
            : (parent.children = [current]);
        } else if (pid === 0) {
          // 合适根文件夹
          arr.push(current);
        }
        return arr;
      }, []);
      this.allData = result;
    },
    isParent(data) {
      return data.type === "parent";
    },
    render(h, { node, data }) {
      console.log(node);
      return (
        <div>
          {this.isParent(data) ? (
            node.expanded ? (
              <i class="el-icon-folder-remove"></i>
            ) : (
              <i class="el-icon-folder-add"></i>
            )
          ) : (
            <i class="el-icon-tickets"></i>
          )}

          {/**<i class="el-icon-folder-remove"></i>**/}

          {data.name}
        </div>
      );
    },
  },
  watch: {
    data() {
      this.transformData();
    },
  },
  mounted() {
    this.transformData();
  },
};
</script>

<style>
</style>